package com.aek.aekdroid.data;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.aek.aekdroid.AekDroidApplication;
import com.aek.aekdroid.Helper;
import com.aek.aekdroid.MyLog;
import com.aek.aekdroid.R;
import com.aek.aekdroid.data.Match.Detail;

public class MatchData extends BasicData {
	public static final String TAG = "MatchData";
	public static final int VALID = 0;
	public static final int DELETED = 1;
	public static final int HOME = 0;
	public static final int VISITOR = 1;
	public static final int GOAL = 0;
	public static final int YELLOW = 1;
	public static final int SECOND_YELLOW = 2;
	public static final int RED = 3;
	public static final String ALL = "Όλες";
	public static String tournament = ALL;
	public static final String[] ICONS = { "goal", "yellow", "yellow_red", "red", "post", "lost_penalty", "in", "out" };
	public static Map<String, String[]> players = new HashMap<String, String[]>();

	private Context c;

	public MatchData(Context context) {
		super(context);
		this.c = context;
		players.put("2011-2012", new String[] { "Αραμπατζής", "Κωνσταντόπουλος", "Μοσχονάς", "Γεωργέας", "Καράμπελας", "Κοντοές", "Δέλλας",
				"Μανωλάς", "Χέλγκασον", "Καλά", "Μπουγαΐδης", "Εγγλέζου", "Τσουκαλάς", "Καφές", "Μάκος", "Λαγός", "Γκερέιρο", "Λεονάρντο",
				"Γκέντζογλου", "Κατσέτης", "Αγκριμπά", "Κλωναρίδης", "Κάρλος", "Γκούντγιονσεν", "Λυμπερόπουλος", "Μπέλεκ", "Σιαλμάς",
				"Μπερνς", "Τσίτας", "Νικολτσής", "Βάργκας", "Αργυρίου", "Ρίκκα" });
		MyLog.i(TAG, "Initializing data");
	}

	public void update(ContentValues values, int id) {
		super.update(IDbConstants.MATCHES_TABLE, values, id);
	}

	public void insertOrUpdate(ContentValues values, ArrayList<Detail> details) {
		MyLog.i(TAG, "Insert or update on " + values);
		super.insertOrUpdate(IDbConstants.MATCHES_TABLE, values, details);
	}

	public Cursor getMatches() {
		SQLiteDatabase db = dbHelper.getReadableDatabase();
		AekDroidApplication aek = (AekDroidApplication) c.getApplicationContext();
		String limitStr = aek.getPrefs().getString(aek.getString(R.string.pref_maxMatchesKey), "100");

		String period = aek.getPrefs().getString(aek.getString(R.string.pref_periodKey), Helper.getDefaultPeriod());
		int limit = 10;
		String where = IDbConstants.MATCHES_C_DELETED + "=? AND " + IDbConstants.MATCHES_C_PERIOD + " = ? ";
		String[] whereClause = null;
		if (tournament.equals(ALL)) {
			whereClause = new String[] { "0", period };
		} else {
			where = IDbConstants.MATCHES_C_DELETED + "=? AND " + IDbConstants.MATCHES_C_PERIOD + " = ? AND "
					+ IDbConstants.MATCHES_C_TOURNAMENT + " = ?";
			whereClause = new String[] { "0", period, tournament };
		}
		try {
			limit = Integer.parseInt(limitStr);
		} catch (NumberFormatException e) {

		}

		return db.query(MATCHES_TABLE, null, where, whereClause, null, null, MATCHES_C_DATETIME + " DESC", String.valueOf(limit));
	}

	public Cursor getMatch(int _id) {
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		Cursor c = db.query(MATCHES_TABLE, null, MATCHES_C_ID + " = ? ", new String[] { String.valueOf(_id) }, null, null, null, "1");
		return c;
	}

	public long getLastTimeUpdated() {
		SQLiteDatabase db = dbHelper.getReadableDatabase();
		AekDroidApplication aek = (AekDroidApplication) c.getApplicationContext();
		String period = aek.getPrefs().getString(aek.getString(R.string.pref_periodKey), Helper.getDefaultPeriod());
		Cursor cursor = null;
		try {
			cursor = db.query(MATCHES_TABLE, new String[] { "updated" }, MATCHES_C_PERIOD + " = '" + period + "'", null, null, null,
					MATCHES_C_UPDATED + " DESC", "1");
			if (cursor.moveToFirst()) {
				long time = cursor.getLong(cursor.getColumnIndex(MATCHES_C_UPDATED));
				return time;
			}
			cursor.close();
			return 0;
		} finally {
			if (cursor != null) {
				cursor.close();
			}
			dbHelper.close();
		}

	}

	public int purge() {
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		db.beginTransaction();
		try {
			int matches = db.delete(MATCHES_TABLE, "1", null);
			db.delete(DETAILS_TABLE, null, null);
			db.setTransactionSuccessful();
			db.endTransaction();
			return matches;
		} catch (Exception ex) {
			db.endTransaction();
			return -1;
		} finally {
			db.close();
		}

	}

	public Cursor getMatchDetails(int match_id) {
		SQLiteDatabase db = dbHelper.getReadableDatabase();
		return db.query(DETAILS_TABLE, null, IDbConstants.DETAILS_C_DELETED + "=? AND " + IDbConstants.DETAILS_C_MATCH_ID + " = ? ",
				new String[] { "0", String.valueOf(match_id) }, null, null, DETAILS_C_MIN + " ASC", null);
	}

	public String getMatchFullTitle(int matchId) {
		Cursor cursor = getMatch(matchId);
		try {
			if (cursor.moveToFirst()) {
				return cursor.getString(cursor.getColumnIndex(IDbConstants.MATCHES_C_HOME_TEAM)) + "-"
						+ cursor.getString(cursor.getColumnIndex(IDbConstants.MATCHES_C_AWAY_TEAM)) + "="
						+ cursor.getString(cursor.getColumnIndex(IDbConstants.MATCHES_C_HOME_GOALS)) + "-"
						+ cursor.getString(cursor.getColumnIndex(IDbConstants.MATCHES_C_AWAY_GOALS));
			}
			return "";
		} finally {
			cursor.close();
		}
	}

	public Cursor getMatchDetail(int id) {
		SQLiteDatabase db = dbHelper.getReadableDatabase();
		return db.query(DETAILS_TABLE, null, IDbConstants.DETAILS_C_ID + " = ? ", new String[] { String.valueOf(id) }, null, null, null,
				"1");
	}

	public String getMatchEleven(int matchId) {
		Cursor cursor = getMatch(matchId);
		try {
			if (cursor.moveToFirst()) {
				return cursor.getString(cursor.getColumnIndex(IDbConstants.MATCHES_C_PLAYERS));
			}
			return "";
		} finally {
			cursor.close();
		}
	}

	public ArrayList<CalendarMatch> getCalendarMatches() {
		ArrayList<CalendarMatch> matches = new ArrayList<CalendarMatch>();
		SQLiteDatabase db = dbHelper.getReadableDatabase();
		Cursor cursor = db.query(MATCHES_TABLE, null, IDbConstants.MATCHES_C_DATETIME + " > ? ",
				new String[] { String.valueOf(System.currentTimeMillis()) }, null, null, null, null);
		while (cursor.moveToNext()) {
			int id = cursor.getInt(cursor.getColumnIndex(IDbConstants.MATCHES_C_ID));
			String calId = cursor.getString(cursor.getColumnIndex(IDbConstants.MATCHES_C_CALENDAR_ID));
			String homeTeam = cursor.getString(cursor.getColumnIndex(IDbConstants.MATCHES_C_HOME_TEAM));
			String awayTeam = cursor.getString(cursor.getColumnIndex(IDbConstants.MATCHES_C_AWAY_TEAM));
			long datetime = cursor.getLong(cursor.getColumnIndex(IDbConstants.MATCHES_C_DATETIME));
			int deleted = cursor.getInt(cursor.getColumnIndex(IDbConstants.MATCHES_C_DELETED));
			String tournament = cursor.getString(cursor.getColumnIndex(IDbConstants.MATCHES_C_TOURNAMENT));
			String stadium = cursor.getString(cursor.getColumnIndex(IDbConstants.MATCHES_C_STADIUM));
			matches.add(new CalendarMatch(id, homeTeam, awayTeam, datetime, tournament, stadium, calId, deleted));
		}
		cursor.close();
		db.close();
		return matches;
	}
}
